<template>
  <div>
    <br />
    <div>
      <i class="el-icon-paperclip" style="margin-left: 10px;"/>
      <span> 充值管理</span>
    </div>
    <el-card style="width: 98%; margin-left: 10px;">
      <br />
      <el-row>
        <el-col :span="20">
          <el-alert style="width: 70%;margin-left: 240px;"
            :title="title" type="success"
            center :closable="false">
          </el-alert>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-coin" size="medium" 
          style="margin-left: 30px;" @click="rechargeBtn">会员卡充值</el-button>
        </el-col>
      </el-row>
      <br />
      <el-table :data="rechargeList" height="580"
      row-key="id" :default-expand-all=true
      :default-sort = "{prop: 'date', order: 'descending'}"
      :header-cell-style="{'text-align':'center'}"
      :cell-style="{'text-align':'center'}"
      :row-class-name="tableClass"
      style="width: 98%;margin-left: 10px;margin-top: 20px;">
        <el-table-column prop="date" label="日期" width="220px"></el-table-column>
        <el-table-column prop="dealId" label="交易单号" width="240px"></el-table-column>
        <el-table-column prop="cardId" label="会员卡号" width="220px"></el-table-column>
        <el-table-column prop="userName" label="充值会员" width="180px"></el-table-column>
        <el-table-column prop="price" label="充值金额" width="220px">
          <template slot-scope="scope">
            <span v-if="scope.row.children===null" style="color: saddlebrown;">￥</span>
            <span v-text="scope.row.price" style="color: saddlebrown;"></span>
          </template>
        </el-table-column>
        <el-table-column prop="payment" label="支付方式" width="160px">
          <template slot-scope="scope">
            <div v-if="scope.row.payment===1">
              <el-tag type="success" style="font-size: 15px;" v-if="scope.row.mode==='微信'">微信</el-tag>
              <el-tag type="primary" style="font-size: 15px;" v-if="scope.row.mode==='支付宝'">支付宝</el-tag>
            </div>
            <el-tag type="warning" style="font-size: 15px;" v-if="scope.row.payment===0">现金</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dealTime" label="充值时间" width="280px"></el-table-column>
      </el-table>
      <br />
    </el-card>

    <!-- 会员卡充值对话框 -->
    <el-dialog title="会员卡充值" :visible.sync="rechargeDialog" width="40%" @close="closeRechargeDialog">
      <el-form :model="cardForm" :rules="cardRules" ref="cardFormRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="会员卡号" prop="changeList" style="width: 90%;">
              <el-cascader v-model="cardForm.changeList" :options="userList" :props="props" filterable
              :show-all-levels="false" @change="changeMoney"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员卡余额" prop="money" style="width: 90%;">
              <el-input v-model="cardForm.money" readonly @focus="warning"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="充值金额" prop="price" style="width: 90%;">
              <el-input v-model="rechargeForm.price" @input="getReturnMoney"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="payment">
              <el-select v-model="rechargeForm.payment">
                <el-option label="电子支付" value="1"></el-option>
                <el-option label="现金支付" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="rechargeForm.payment==1">
            <el-form-item label="支付渠道" prop="mode">
              <el-select v-model="rechargeForm.mode">
                <el-option value="微信"></el-option>
                <el-option value="支付宝"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="rechargeForm.payment==0">
          <el-col :span="12">
            <el-form-item label="实际支付" prop="realMoney" style="width: 90%;">
              <el-input v-model="rechargeForm.realMoney" @input="getReturnMoney"/>
            </el-form-item>
          </el-col>
          <el-col :span="12"
                  v-if="rechargeForm.realMoney!==''
                  &&rechargeForm.realMoney!==null
                  &&rechargeForm.price!==''
                  &&rechargeForm.price!==null">
            <el-form-item label="零钱找回" prop="returnMoney" style="width: 90%;">
              <el-input v-model="rechargeForm.returnMoney" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rechargeDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRecharge">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    created(){
      this.getUserAndCard()
      this.getCardList()
      this.getRechargeList()
    },
    data(){
      const checkPrice = (rule, value, callback) => {
        //定义充值金额的正则表达式  JS中用/来表示正则表达式的开始和结束
        const priceRege =
          /(^[1-9]{1}[0-9]*$)|(^0[\.]{1}0[1-9]{1}$)|(^0[\.]{1}[1-9]{1}[0-9]{0,1}$)|(^[1-9]{1}[0-9]*[\.]{1}[0-9]{1,2}$)/
        // const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
        //正则表达式语法校验  test(xx) 校验成功 返回true  校验失败返回false
        if (priceRege.test(value)) {
          //表示金额合法 正确返回
          return callback()
        }
        callback(new Error('请填写正确的充值金额'))
      }
      return{
        title:'您 好 ， 欢 迎 进 入 充 值 管 理 界 面 ！',
        userList:[],
        cardList:[],
        rechargeList:[],
        rechargeDialog:false,
        rechargeForm:{
          price: null,
          realMoney: null,
          returnMoney: null
        },
        cardForm:{
          money:null
        },
        //定义级联选择项
        props: {
          //定义子节点菜单展开方式
          expandTrigger: "hover",
          value: "userName", //选中数据的value值
          label: "userName", //选中数据展现名称
          children: "children" ,//自选项数据
        },
        cardRules: {
          changeList: [{
            required: true,
            message: '请选择会员卡',
            trigger: 'blur'
          }],
          money: [{
              required: true,
              message: '会员卡余额不能为空',
              trigger: 'blur'
            }
          ]
        },
        rechargeRules: {
          price: [{
              required: true,
              message: '请输入要充值的余额',
              trigger: 'blur'
            },
            {
              validator: checkPrice,
              trigger: 'blur'
            }
          ],
          payment: [{
            required: true,
            message: '请选择支付方式',
            trigger: 'blur'
          }],
          mode: [{
            required: true,
            message: '请选择支付渠道',
            trigger: 'blur'
          }],
          realMoney: [{
              required: true,
              message: '请输入实际支付的金额',
              trigger: 'blur'
            },
            {
              validator: checkPrice,
              trigger: 'blur'
            }
          ],
          returnMoney: [{
            required: true,
            trigger: 'blur'
          }]
        }
      }
    },
    methods:{
      async getRechargeList(){
        const {data: result} =await this.$http.get(`recharge/getRechargeList`)
        this.rechargeList=result.data
      },
      tableClass({row}) {
        if (row.children !== null) {
          return 'primary-row'
        }
        return ''
      },
      async getCardList(){
        const {data: result} =await this.$http.get(`card/list?query=`+'')
        this.cardList=result.data
      },
      async getUserAndCard(){
        const {data: result} =await this.$http.get(`user/getUserAndCard`)
        this.userList=result.data
      },
      warning() {
        this.$notify.warning({
          title: '注意',
          dangerouslyUseHTMLString: true,
          message: '<div>会员卡余额无需手动输入</div><div>选择会员卡后，余额会自动显示</div>',
          offset: 100
        });
      },
      changeMoney(){
        this.cardForm.id=this.cardForm.changeList[1]
        for(let card of this.cardList){
          if(this.cardForm.id===card.id){
            this.cardForm.money=card.money
            break
          }
        }
      },
      getReturnMoney() {
        this.rechargeForm.returnMoney = this.rechargeForm.realMoney - this.rechargeForm.price
        if (this.rechargeForm.returnMoney < 0) this.rechargeForm.returnMoney = null
      },
      closeRechargeDialog(){
        this.$refs.cardFormRef.resetFields()
        this.$refs.rechargeFormRef.resetFields()
        this.cardForm={
          money:null
        }
        this.rechargeForm = {
          price: null,
          realMoney: null,
          returnMoney: null
        }
      },
      rechargeBtn(){
        this.rechargeDialog=true
      },
      async saveRecharge(){
        if (this.rechargeForm.payment == 0) {
          if(this.rechargeForm.realMoney!==''
            &&this.rechargeForm.realMoney!==null
            &&this.rechargeForm.price!==''
            &&this.rechargeForm.price!==null){
            if (this.rechargeForm.returnMoney === null) {
              this.$message.error("当前金额不足以完成支付操作!")
              return
            }
          }
        }
        this.$refs.cardFormRef.validate(async valid1 => {
          this.$refs.rechargeFormRef.validate(async valid2 => {
            //如果校验失败 则停止数据
            if (!valid1||!valid2) return
            this.cardForm.price=this.rechargeForm.price
            this.rechargeForm.cardId=this.cardForm.id
            let form={
              card:this.cardForm,
              recharge:this.rechargeForm
            }
            const {data: result} =await this.$http.put(`card/updateMoney`,form)
            if(result.status !== 200 ) return this.$message.error("会员卡充值失败!")
            // this.$message.success("会员卡充值成功!")
            this.title=`充 值 成 功 ！${this.cardForm.id} 会 员 卡 已 到 账 ${this.rechargeForm.price} 元 ！`
            this.getCardList()
            this.getRechargeList()
            this.rechargeDialog=false
          })
        })
      }
    }
  }
</script>

<style>
  .el-table .primary-row {
    background: #f4f7f9;
  }
</style>
